<!-- 框架合同申请变更 -->
<template>
    <view>
      <u-form
        :model="model"
        :rules="rules"
        ref="form"
        labelPosition="top"
        labelWidth="auto"
        :labelStyle="{
                  fontSize: '14px',
                  color: '#B2B2B2',
                  lineHight: '20px'
        }"
      >
        <view class="basic-style">
          <view class="basic-title basic-border">基本信息</view>
          <u-form-item label="单据编号" prop="htbh" required>
            <u--input v-model="model.htbh" disabled></u--input>
          </u-form-item>
          <u-form-item label="申请人" prop="propose" required>
            <h-select-person-input
              style="width: 100%"
              disabled
              v-model="model.proposer"
              placeholder="请选择申请人"
              border="surround"
              suffixIcon="arrow-down-fill"
              :suffixIconStyle="{ color: '#B2B2B2' }"
              objectField="model.proposer"
            ></h-select-person-input>
          </u-form-item>
          <u-form-item label="申请部门" prop="proposerDeptId" required>
            <h-select-depart-input
              disabled
              v-model="model.proposerDeptId"
              :departName="model.proposerDeptText"
              placeholder="请选择部门"
              border="surround"
              style="width: 100%"
              suffixIcon="arrow-down-fill"
              :suffixIconStyle="{ color: '#B2B2B2' }"
              :title.sync="model.proposerDeptText"
            ></h-select-depart-input>
          </u-form-item>
                  <u-form-item label="申请时间" required>
                      <u--input v-model="model.createTime" disabled></u--input>
                  </u-form-item>
                  <u-form-item label="合同编号" prop="caId" required>
                      <h-select-contract-manager-input
                          v-model="model.caId"
                          objectField="model.caId"
                          placeholder="请选择合同编号"
                          border="surround"
                          :allList="true"
                          :status="'2,3,7'"
                          :muitFlag="true"
                          :changeStatus="'unchanged'"
                          style="width: 100%;"
                          htlx="3"
                          :triggerChange="true"
                          suffixIcon="arrow-down-fill"
                          :suffixIconStyle="{color: '#B2B2B2'}"
                          @input="htbhChange"
                      >
                      </h-select-contract-manager-input>
                  </u-form-item>
                          <u-form-item label="合同名称" prop="htmc" required>
                              <u--input v-model="model.htmc" placeholder="请输入合同名称"></u--input>
                          </u-form-item>
                  <u-form-item label="变更类型" prop="bglx" required>
                      <h-select-input-tag
                          style="width: 100%;"
                          v-model="model.bglx"
                          objectField="model.bglx"
                          placeholder="请选择变更类型"
                          suffixIcon="arrow-down-fill"
                          :suffixIconStyle="{ color: '#B2B2B2' }"
                          border="surround"
                          dictName="kjht_bglx_type"
                      ></h-select-input-tag>
                  </u-form-item>
          
          <!-- <u-form-item label="项目名称" prop="xmmc" required>
                      <h-select-project-input-popup
                          disabled
                          :proDisabled="true"
                          :projectStatus="'2'"
                          ref="projectSelect"
                          v-model="model.xmmc"
                          style="width: 100%"
                          placeholder="请选择项目名称"
                          border="surround"
                          isOldSystem="!1"
                          suffixIcon="arrow-down-fill"
                          :suffixIconStyle="{ color: '#B2B2B2' }"
                          @change="xmmcChange"
                          @input="xmmcInput"
                      ></h-select-project-input-popup>
          </u-form-item> -->
          <u-form-item label="经营团队" prop="jytd" required>
            <h-select-team-input-popup
                        @change="changeBusinessCompany"
              style="width: 100%"
              v-model="model.jytd"
              placeholder="请选择经营团队"
              :tdlx="1"
                          suffixIcon="arrow-down-fill"
                          :suffixIconStyle="{ color: '#B2B2B2' }"
              border="surround"
            ></h-select-team-input-popup>
          </u-form-item>
                  <!-- <u-form-item
                  label="经营公司"
                  prop="businessCompanyId"
                  :borderBottom="false"
                  required>
                  <h-select-company-input
                      disabled
                      style="width: 100%"
                      v-model="model.businessCompanyId"
                      border="surround"
                      placeholder="请选择经营公司"
                      suffixIcon="arrow-down-fill"
                      :suffixIconStyle="{color: '#B2B2B2'}"
                  ></h-select-company-input>
                </u-form-item> -->
          <u-form-item
              label="业绩归属年度"
              prop="yjgsnd"
              :borderBottom="false"
              required>
              <h-dict-select
                  style="width: 100%" 
                  v-model="model.yjgsnd" 
                  placeholder="请选择业绩归属年度" 
                  dictName="yjgsnd" 
                  suffixIcon="arrow-down-fill" 
                  :suffixIconStyle="{color: '#B2B2B2'}"
              ></h-dict-select>
          </u-form-item>
          <u-form-item label="签订单位" prop="qddw" required>
            <h-select-company-input
              style="width: 100%"
              v-model="model.qddw"
              border="surround"
              placeholder="请选择签订单位"
              suffixIcon="arrow-down-fill"
              :suffixIconStyle="{ color: '#B2B2B2' }"
              objectField="model.qddw"
            ></h-select-company-input>
          </u-form-item>
          <u-form-item label="项目承接人" prop="xmcjr" required>
            <h-select-person-input-popup
              v-model="model.xmcjr"
              style="width: 100%;"
              placeholder="请选择项目承接人"
              searchPlaceholder="请输入"
              border="surround"
              suffixIcon="arrow-down-fill"
              :suffixIconStyle="{ color: '#B2B2B2' }"
            ></h-select-person-input-popup>
          </u-form-item>
          <u-form-item label="业主单位" prop="yzdw" required>
            <h-select-customer-input
              style="width: 100%"
              v-model="model.yzdw"
              objectField="model.yzdw"
              commercialType="1"
                          suffixIcon="arrow-down-fill"
                          :suffixIconStyle="{ color: '#B2B2B2' }"
              placeholder="请选择业主单位"
              border="surround"
                          @input="yzdwChange"
            ></h-select-customer-input>
          </u-form-item>
          <u-form-item label="联系人" prop="lxr">
            <h-select-input-tag
              style="width: 100%;"
              v-model="model.lxr"
              objectField="model.lxr"
              placeholder="请选择联系人"
              border="surround"
                          suffixIcon="arrow-down-fill"
                          :suffixIconStyle="{ color: '#B2B2B2' }"
              :dictName="cust_lxr"
                          errorMessage="请选择业主单位"
              @change="lxrChange"
            ></h-select-input-tag>
          </u-form-item>
          <u-form-item label="联系方式" prop="lxfs">
            <u--input v-number-normal placeholder="请输入联系方式" v-model="model.lxfs"></u--input>
          </u-form-item>
          <u-form-item label="签订日期" prop="qdrq">
            <h-time-select
              disabled
              mode="date"
              ref="remittanceDate"
              v-model="model.qdrq"
              placeholder="请选择签订日期"
              border="surround"
              suffixIcon="calendar-fill"
              :suffixIconStyle="{ color: '#B2B2B2' }"
            ></h-time-select>
          </u-form-item>
          <!-- <u-form-item label="履约保证金(元)" prop="bail" required>
                      <h-money-input
                          placeholder="请输入履约保证金"
                          v-model="model.bail"
                      ></h-money-input>
          </u-form-item>
                  <u-form-item label="分配方式" prop="distributionMethod" required>
                    <h-select-input-tag
                      style="width: 100%;"
                      v-model="model.distributionMethod"
                      objectField="model.distributionMethod"
                      placeholder="请选择是分配方式"
                          suffixIcon="arrow-down-fill"
                          :suffixIconStyle="{ color: '#B2B2B2' }"
                      border="surround"
                          @change="changeMoney"
                      dictName="distribution_method"
                    ></h-select-input-tag>
                  </u-form-item> -->
          <u-form-item label="是否用印" prop="sfyz" required>
            <h-select-input-tag
              style="width: 100%;"
              v-model="model.sfyz"
              objectField="model.sfyz"
              placeholder="请选择是否用印"
                          suffixIcon="arrow-down-fill"
                          :suffixIconStyle="{ color: '#B2B2B2' }"
              border="surround"
              dictName="yn"
                          @change="handleRules"
            ></h-select-input-tag>
          </u-form-item>
                  <view v-if="model.sfyz === '1'">
                      <u-form-item label="用印类型" prop="signSealWay" required>
                          <h-select-input-tag
                              class="w-100"
                              v-model="model.signSealWay"
                              objectField="model.signSealWay"
                              placeholder="请选择用印类型"
                              suffixIcon="arrow-down-fill"
                              :suffixIconStyle="{ color: '#B2B2B2' }"
                              border="surround"
                              dictName="seal_way"
                              @change="handleSignSealWay"
                          ></h-select-input-tag>
                      </u-form-item>
                      <u-form-item label="印章类型" prop="yzlx" required>
                          <h-dict-select
                              v-model="model.yzlx"
                              style="width: 100%" 
                              placeholder="请选择印章类型"
                              dictName="yzlx_type"
                              border="surround"
                              suffixIcon="arrow-down-fill"
                              :suffixIconStyle="{color: '#B2B2B2'}"
                          ></h-dict-select>
                      </u-form-item>
                      <u-form-item label="用印份数" prop="yyfs" required>
                          <h-number-input placeholder="请输入用印份数" v-model="model.yyfs" :digit="0" :min="1"></h-number-input>
                      </u-form-item>
                  </view>
 
                  <u-form-item label="是否存档" prop="sfcd">
                    <h-select-input-tag
                          disabled
                      class="w-100"
                      v-model="model.sfcd"
                      objectField="model.sfcd"
                      placeholder="请选择是否存档"
                          suffixIcon="arrow-down-fill"
                          :suffixIconStyle="{ color: '#B2B2B2' }"
                      border="surround"
                      dictName="yn"
                          @change="handleRules2"
                    ></h-select-input-tag>
                  </u-form-item>
                  <view v-if="model.sfcd === '1'">
                    <u-form-item label="合同存档份数" prop="cdfs">
                      <h-number-input placeholder="请输入合同存档份数" disabled v-model="model.cdfs" :digit="0" :min="0"></h-number-input>
                    </u-form-item>
                  </view>
                  <view v-if="!model.sfyz||model.sfyz=='0'">
                      <u-form-item label="合同原件" prop="masterCopy" required>
                          <view class="space-y-1" style="width: 100%;">
                            <view style="color: red">提示：请等待附件上传完成，再点击保存，否则附件无法保存成功！</view>
                            <h-upload-file v-model="model.masterCopy" :isIcon="false"></h-upload-file>
                            <file-list v-if="model.masterCopy" v-model="model.masterCopy" :isDelete="true"></file-list>
                          </view>
                      </u-form-item>
                  </view>
          <u-form-item label="本次合同额(元)" prop="bchte" required>
            <h-money-input placeholder="请输入本次合同额" v-model="model.bchte" @change="convertMoney2"></h-money-input>
          </u-form-item>
          <u-form-item label="本次合同额大写" prop="bchtedx">
            <u--input disabled placeholder="请输入本次合同额大写" v-model="model.bchtedx"></u--input>
          </u-form-item>
                  <!-- <u-form-item
                      label="经营绩效(元)"
                      prop="businessPerformance"
                      :borderBottom="false"
                      ref="item1"
                      required>
                      <h-money-input
                          type="number"
                          placeholder="请输入经营绩效"
                          v-model="model.businessPerformance"
                      ></h-money-input>
                  </u-form-item> -->
          <u-form-item label="服务期限开始日期" prop="fwqx" required>
            <h-time-select
              mode="date"
              ref="remittanceDate"
              v-model="model.fwqx"
              placeholder="请选择服务期限开始日期"
              border="surround"
              suffixIcon="calendar-fill"
              :suffixIconStyle="{ color: '#B2B2B2' }"
                          @change="handleBorrowDateChange"
            ></h-time-select>
          </u-form-item>
          <u-form-item label="服务期限结束日期" prop="fwqxEnd" required>
            <h-time-select
              mode="date"
              ref="remittanceDate"
              v-model="model.fwqxEnd"
              placeholder="请选择服务期限结束日期"
              border="surround"
              suffixIcon="calendar-fill"
              :suffixIconStyle="{ color: '#B2B2B2' }"
                          :minDate="model.fwqx?(new Date(model.fwqx)).getTime():315504000000"
                          @change="predictReturnDateChange"
            ></h-time-select>
          </u-form-item>
        </view>
  
        <view class="basic-style">
          <view class="basic-title basic-border">委托方(合同甲方)信息</view>
          <view class="space-y-1 py-1">
            <u-button size="small" type="primary" @click="addFormA">新增</u-button>
          </view>
          <view v-for="(item, index) in formDataA" :key="index">
            <!-- <FormAInfo :item="item" :index="index" :signSealWay="model.signSealWay" @edit="handleEditFormA" @remove="handleRemoveFormA" @copy="handleCopyFormA" /> -->
            <clientFormInfo :item="item" :index="index" :signSealWay="model.signSealWay" @edit="handleEditFormA" @remove="handleRemoveFormA" @copy="handleCopyFormA" />
          </view>
          <u-popup mode="bottom" :show="showFormModalA">
            <!-- <FormA ref="dataFormA" :index="index" :signSealWay="model.signSealWay" @submit="handleFormSubmitA" @close="closeFormModalA" /> -->
            <clientFormInfoA ref="dataFormA" :index="index" :signSealWay="model.signSealWay" @submit="handleFormSubmitA" @close="closeFormModalA" />
          </u-popup>
        </view>
  
        <view class="basic-style">
          <view class="basic-title basic-border pt-1">受托方(合同乙方)信息</view>
          <view class="space-y-1 py-1">
            <u-button size="small" type="primary" @click="addFormB">新增</u-button>
          </view>
          <view v-for="(item, index) in formDataB" :key="index">
              <!-- <FormBInfo :item="item" :index="index" :signSealWay="model.signSealWay" @edit="handleEditFormB" @remove="handleRemoveFormB" @copy="handleCopyFormB" /> -->
              <TrusteeFormInfo :item="item" :index="index" :signSealWay="model.signSealWay" @edit="handleEditFormB" @remove="handleRemoveFormB" @copy="handleCopyFormB" />
          </view>
          <u-popup mode="bottom" :show="showFormModalB">
            <!-- <FormB ref="dataFormB" :index="index" :signSealWay="model.signSealWay" @submit="handleFormSubmitB" @close="closeFormModalB" /> -->
            <!-- <FormB ref="dataFormB" :index="index" :signSealWay="model.signSealWay" @submit="handleFormSubmitB" @close="closeFormModalB" /> -->
            <TrusteeFormInfoB ref="dataFormB" :index="index" :signSealWay="model.signSealWay" @submit="handleFormSubmitB" @close="closeFormModalB" />
          </u-popup>
        </view>
  
        <!-- <view class="basic-style">
          <view class="basic-title basic-border pt-1">任务信息</view>
          <TaskInfo :entities="dataSource2" :bchte="model.bchte" :distributionMethod="model.distributionMethod"/>
        </view> -->
  
        <!-- <view class="basic-style">
          <view class="basic-title basic-border">收付款计划</view>
                  <u-form-item label="是否变更款项信息" prop="fwqxEnd">
                      <h-dict-radio v-model="model.sfbgkxxx" dictName="yn"></h-dict-radio>
                  </u-form-item>
                  <view class="space-y-1 py-1" v-if="model.sfbgkxxx == 1">
                      <u-button size="small" type="primary" @click="addFormC">新增</u-button>
                  </view>
                  <view v-for="(item, index) in formDataC" :key="index">
                      <FormCInfo 
                          :item="item" 
                          :index="index" 
                          @edit="handleEditFormC" 
                          @remove="handleRemoveFormC"
                          @copy="handleCopyFormC" 
                          :disabled="model.sfbgkxxx == !1"
                          :showKxxx="model.lx == 2"
                      />
                  </view>
                  <u-popup mode="bottom" :show="showFormModalC" :closeOnClickOverlay="false">
                      <FormC ref="dataFormC" :index="index" :htlx="model.htlx" :projectId="model.xmmc" @submit="handleFormSubmitC" @close="closeFormModalC" />
                  </u-popup>
              </view> -->
  
        <view class="basic-style">
          <u-form-item label="备注" prop="bz">
                      <!-- #ifdef H5 -->
                      <u--textarea confirm-type="done" v-model="model.bz" placeholder="请输入备注" maxlength="500"></u--textarea>
                      <!-- #endif -->
                      <!-- #ifndef H5 -->
                      <u--textarea :confirm-type="null" count v-model="model.bz" placeholder="请输入备注" maxlength="500"></u--textarea>
                      <!-- #endif -->
          </u-form-item>
          <u-form-item label="邮寄信息" prop="yjxx">
                      <!-- #ifdef H5 -->
                      <u--textarea confirm-type="done" v-model="model.yjxx" placeholder="请输入邮寄信息" maxlength="500"></u--textarea>
                      <!-- #endif -->
                      <!-- #ifndef H5 -->
                      <u--textarea :confirm-type="null" count v-model="model.yjxx" placeholder="请输入邮寄信息" maxlength="500"></u--textarea>
                      <!-- #endif -->
          </u-form-item>
          <u-form-item label="变更说明" prop="contractChangeReason" required>
                      <!-- #ifdef H5 -->
                      <u--textarea confirm-type="done" v-model="model.contractChangeReason" placeholder="请输入变更说明" maxlength="500"></u--textarea>
                      <!-- #endif -->
                      <!-- #ifndef H5 -->
                      <u--textarea :confirm-type="null" count v-model="model.contractChangeReason" placeholder="请输入变更说明" maxlength="500"></u--textarea>
                      <!-- #endif -->
          </u-form-item>
        </view>
              
              <view class="basic-style" v-if="model.sfyz == 1">
                <view class="basic-title basic-border">用印文件<span style="color: #faad14;font-weight: 600">（请上传只需盖章的用印文件！）</span></view>
                <u-form-item label="用印文件" prop="" required>
                      <view class="py-1 space-y-1" style="width: 100%">
                          <view style="color: red">提示：请等待附件上传完成，再点击保存，否则附件无法保存成功！</view>
                          <h-upload-file v-model="model.signFile" :fillSize="50" :isIcon="false" :isSingle="true" fileType=".pdf, .PDF, .doc, .docx" fileTypeText="请上传word与pdf格式的文件！"></h-upload-file>
                          <file-list v-if="model.signFile" v-model="model.signFile" :isDelete="true"></file-list>
                      </view>
                  </u-form-item>
              </view>
        <view class="basic-style">
          <view class="basic-title basic-border">相关附件</view>
          <view class="py-1 space-y-1" style="width: 100%">
            <view style="color: red">提示：请等待附件上传完成，再点击保存，否则附件无法保存成功！</view>
            <h-upload-file v-model="model.xgfj" :isIcon="false"></h-upload-file>
            <file-list v-if="model.xgfj" v-model="model.xgfj" :isDelete="true"></file-list>
          </view>
        </view>
  
        <view class="space-x-1 px-1 btn_position">
                  <u-button type="primary" :disabled="isSubmit" :plain="true" text="保存" @click="onDraft"></u-button>
          <u-button type="primary" :disabled="isSubmit" text="保存并提交" @click="onSubmit"></u-button>
         
        </view>
              <view style="height: 100rpx;"></view>
      </u-form>
          <ProcessNodeConfiguration ref="processConfig" @ok="onOk"></ProcessNodeConfiguration>
          <u-toast ref="uToast"></u-toast>
    </view>
  </template>
  
  <script>
  import { mapState } from 'vuex'
  import moment from 'moment'
  import { gainBillNo, add, info, edit,checkContractById } from '@/api/finance/ErpFinanceInvoiceApplicationBillForm'
  import { convertCurrency } from '@/utils/utils'
  import { filterMultiDictText, initDictOptions } from '@/utils/JDictSelectUtil.js'
  import {
    addInvoiceHandleRecordList,
    erpOmcProjectId,
    relationTaskList,
    erpFinanceProjectDepositBillqueryByEntity,
    querySupplierByIdserpOmcProjectId,
    erpOmcContractManagerFinalQueryById,
    erpOmcContractManagerPlanFinalList,
    erpOmcContractManagerClassFinalList,
    erpOmcContractManagerTrusteeFinalList,
    erpOmcContractManagerEntrustFinalList,
    erpOmcCustomerManagerContactId,
      erpOmcContractManagerClassListAll, // 任务信息
      erpOmcProjectTaskListById,// 任务信息2
      listContractFinalTaskByProjectId, // 选择合同时查询的任务
    erpOmcContractManagerEntrustListAll, // 委托方
    erpOmcContractManagerTrusteeListAll, // 受托方
    erpOmcContractManagerPlanListAll, // 收付款计划
  } from '@/api/index'
  import fileList from '@/pages/synergy/components/fileList.vue'
  import PrincipalForm from './components/PrincipalForm.vue'
  import PrincipalFormInfo from './components/PrincipalFormInfo.vue'
  import FormA from './components/FormA.vue'
  import FormAInfo from './components/FormAInfo.vue'
  import FormB from './components/FormB.vue'
  import FormBInfo from './components/FormBInfo.vue'
  import FormC from './components/FormC.vue'
  import FormCInfo from './components/FormCInfo.vue'
  import TaskInfo from './components/TaskInfo.vue'
  import clientFormInfo from './components/clientFormInfo.vue'
  import TrusteeFormInfo from './components/TrusteeFormInfo.vue'
  import TrusteeFormInfoB from './components/TrusteeFormInfoB.vue'
  import clientFormInfoA from './components/clientFormInfoA.vue'
  import ProcessNodeConfiguration from '@/components/ProcessNodeConfiguration/ProcessNodeConfiguration.vue' // 流程节点配置人员选择弹窗
  import Decimal from "decimal.js"
  export default {
    name: 'ErpOmcContractApplicationChangeForm',
    components: { fileList,clientFormInfo,PrincipalForm,TrusteeFormInfoB,TrusteeFormInfo,clientFormInfoA,PrincipalFormInfo, FormA, FormAInfo, FormB, FormBInfo, FormC, FormCInfo, TaskInfo,ProcessNodeConfiguration },
    data() {
      return {
              isSubmit: false,
              projectName: '', // 项目名称
              flag: false,
              cust_lxr: '',
              backUpApplicant: '',
              backUpTeamId: '',
              isReset: false,
              resetKey: '',
              index: null,
              id: '',
              dataSource2: [],
              basicFormA: {},
              basicFormB: {},
              basicFormC: {},
              showFormModalA: false,
              showFormModalB: false,
              showFormModalC: false,
              // formDataA: [{ khdaId: '1598142020751310849', isFk: '1' }],
              formDataA: [],
              formDataB: [],
              formDataC: [],
              contractType: 1, // 代表项目收款合同， 2 代表项目付款合同
              model: {
                  // 基本信息 - 公用
                  bpmBizTitle: '',
                  businessCompanyId:'', // 经营公司
                  lx: 2, // 项目收款合同申请
                  htbh: '',
                  bglx:'',
                  htlx: 3,
                  caId: '',
                  bgsm: '',
                  contractChangeReason:'',
                  proposer: '',
                  sfbgkxxx: 0,
                  proposerDeptId: '',
                  createTime: '',
                  // 基本信息 - 非公用
                  masterCopy: null,
                  yjgsnd: '', // 年度
                  distributionMethod: '',// 分配方式
                  bchte: '',
                  businessPerformance: '', // 经营绩效
                  // 附件
                  xgfj: null,
                  signFile: null, // 用印文件
                  sfcd: '', // 是否存档
                  cdfs: null, // 存档份数
                  signSealWay: '', // 用印类型
              },
              rules: {
                  htbh: [{ required: true, message: '请输入单据编号!', trigger: ['blur', 'change'] }],
                  proposerDeptId: [{ required: true, message: '请选择申请部门!', trigger: ['blur', 'change'] }],
                  proposer: [{ required: true, message: '请选择申请人!', trigger: ['blur', 'change'] }],
                  createTime: [{ required: true, message: '请选择申请时间!', trigger: ['blur', 'change'] }],
                  caId: [{ required: true, message: '请选择合同编号!' }],
                  bglx: [{ required: true, message: '请选择变更类型!' }],
                  sfyz: [{ required: true, message: '请选择是否用印!' }],
                  noFormalContract: [{ required: true, message: '请选择无正式合同!' }],
                  signSealWay: [{ required: true, message: '请选择用印类型!' }],
                  signFile: [{ required: true, message: '请上传用印文件!' }],
                  distributionMethod: [{ required: true, message: '请选择分配方式!' }],
                  bchte: [{ required: true, message: '请输入本次合同额!' }],
                  businessPerformance: [{ required: true, message: '请输入经营绩效!' }],
                  fwqx: [{ required: true, message: '请选择服务期限开始日期!' }],
                  fwqxEnd: [{ required: true, message: '请选择服务期限结束日期!' }],
                  htlx: [{ required: true, message: '请选择合同类型!' }],
                  htmc: [{ required: true, message: '请输入合同名称!' }],
                  xmmc: [{ required: true, message: '请选择项目名称!' }],
                  jytd: [{ required: true, message: '请选择经营团队!' }],
                  yjgsnd: [{ required: true, message: '请选择业绩归属年度!' }],
                  qddw: [{ required: true, message: '请选择签订单位!' }],
                  xmcjr: [{ required: true, message: '请选择项目承接人!' }],
                  yzdw: [{ required: true, message: '请选择业主单位!' }],
                  contractChangeReason: [{ required: true, message: '请输入变更说明!' }],
                  // yzlx: [{ required: true, message: '请选择印章类型!' }],
                  // yyfs: [
                  //   { required: true, message: '请填写用印份数!', trigger: 'blur' },
                  //   { pattern: /^[0-9]*[1-9][0-9]*$/, message: '请输入正整数!' },
                  // ],
                  lxfs: [
                      { required: false },
                      { pattern: /(^1\d{10}$|^(0\d{2,3}-?|\(0\d{2,3}\))?[1-9]\d{4,7}(-\d{1,8})?$)|(^\/$)/, message: '请输入正确的联系方式!',trigger: ['blur','change'] },
                  ],
                  masterCopy: [{ required: true, message: '请上传合同原件!' }],
                  // sfcd: [{ required: true, message: '请选择是否存档!' }],
                  bail: [{ required: true, message: '请输入履约保证金!', trigger: 'blur'}]
              },
              // 代码生成后需手动设置流程编码
              flowCode: 'dev_erp_omc_contract_manager_005',
              formUrl: 'erp/omc/contractmanager/ErpOmcContractApplicationForm',
              formUrlMobile: '/pages/synergy/ErpOmcContractApplicationList',
              beanName: 'ErpFrameworkContractFlow',
              processId: '1557651427069722625',
              dictOptions: {},
      }
    },
    onLoad({ id }) {
      this.id = id || ''
          if (this.id) {
            this.initInfo()
          } else {
            this.initForm()
            this.initBillNo()
          }
          this.initDictConfig()
    },
    computed: {
      ...mapState(['userInfo']),
      formTotal() {
        return this.formDataA.reduce((total, item) => total + Number(item.amount), 0).toFixed(2)
      }
    },
    methods: {
       
          changeBusinessCompany(val){
              this.model.businessCompanyId = val.belongCompanyId
          },
  
          initDictConfig() {
              initDictOptions('erp_omc_team_manager,alias_name,id').then((res) => {
                  if (res.success) {
                      this.$set(this.dictOptions, 'sctd', res.result)
                  }
              })
              initDictOptions('erp_employee_file,name,id').then((res) => {
                  if (res.success) {
                      this.$set(this.dictOptions, 'tdfzr', res.result)
                  }
              })
              initDictOptions('erp_company_files,file_name,id').then((res) => {
          if (res.success) {
            this.$set(this.dictOptions, 'gsda', res.result)
          }
        })
          },
          handleBorrowDateChange(date, dateStr) {
            this.$set(this.model, 'fwqxEnd', undefined)
            this.fwqxEnd = undefined
          },
          predictReturnDateChange (date, dateStr) {
              if (!this.model.fwqx) {
                  return false
              }
              let isBefore = moment(this.model.fwqx).isBefore(this.model.fwqxEnd)
              if (!isBefore) {
                  const format = 'YYYY-MM-DD'
                  const fwqx = moment(this.model.fwqx, format)
                  const fwqxEnd = moment(this.model.fwqxEnd, format)
                  if (fwqx.isSame(fwqxEnd)) {
                      return false
                  }
                  this.$refs.uToast.show({
                      message:'服务期限结束时间必须大于开始时间!'
                  })
                  this.$nextTick(() => {
                      this.model.fwqxEnd = null
                  })
              }
          },
          handleRules(val){
              if(this.model.sfyz == '1'){
                  this.$set(this.rules,'yzlx',[{ required: true, message: '请选择印章类型!' }])
                  this.$set(this.rules,'signFile',[{ required: true, message: '请上传用印文件!' }])
                  this.$set(this.rules,'yyfs',[
                { required: true, message: '请输入用印份数!', trigger: 'blur' },
                { pattern: /^[0-9]*[1-9][0-9]*$/, message: '请输入正整数!' },
              ])
                  this.$delete(this.rules,'masterCopy')
                  this.$set(this.model,'masterCopy','')
              } else {
                  this.$delete(this.rules,'yzlx')
                  this.$delete(this.rules,'yyfs')
                  this.$set(this.model,'yzlx',null)
                  this.$set(this.model,'yyfs',null)
                  this.$set(this.rules,'masterCopy',[{ required: true, message: '请上传合同原件!' }])
                  this.$set(this.model, 'signSealWay', null) // 置空电子签章
              }
              this.$refs.form.clearValidate(['noFormalContract', 'signSealWay', 'yzlx', 'yyfs']);
              if (val == 0) {
                  this.$set(this.model,'noFormalContract','0') // 置空无正式合同
                  if (this.formDataB && this.formDataB.length) {
                      this.formDataB.forEach(value => {
                          value.psnName = null
                          value.psnMobile = null
                          return value
                      })
                  }
                  if (this.formDataA && this.formDataA.length) {
                      this.formDataA.forEach(value => {
                          value.isSignSeal = '0'
                          value.psnName = null
                          value.psnMobile = null
                          return value
                      })
                  }
              } else if (val == '1') {
                  this.$set(this.model,'noFormalContract','') // 置空无正式合同
              }
              
          },
          // 点击选择用印类型
          handleSignSealWay (val) {
              if (val == 'online') {
                  if (this.formDataA && this.formDataA.length) {
                      this.formDataA.forEach(value => {
                          value.isSignSeal = '0'
                          value.psnName = null
                          value.psnMobile = null
                          return value
                      })
                  }
              } else {
                  if (this.formDataB && this.formDataB.length) {
                      this.formDataB.forEach(value => {
                          value.psnName = null
                          value.psnMobile = null
                          return value
                      })
                  }
                  if (this.formDataA && this.formDataA.length) {
                      this.formDataA.forEach(value => {
                          value.isSignSeal = '0'
                          value.psnName = null
                          value.psnMobile = null
                          return value
                      })
                  }
              }
          },
          handleRules2(val){
              if(this.model.sfcd == '1'){
                  // this.$set(this.rules,'cdfs',[
            //     { required: true, message: '请输入合同存档份数!', trigger: 'blur' }
            //   ])
              } else {
                  // this.$delete(this.rules,'cdfs')
                  this.$set(this.model,'cdfs',null)
              }
          },
          // 切换项目 任务信息  数据占比信息改变
          changeMoney(){
              if (this.model.bchte&&this.dataSource2.length) {
                  this.dataSource2.forEach((item) => {
                      if(this.model.distributionMethod==1){
                          // 按比例：更改预计合同额，占比不变、对应的分配合同额实时变化
                          // item.fphte = parseFloat(item.htzb*0.01*parseFloat(this.model.bchte)).toFixed(2)
                          let amount = this.model.bchte * item.htzb / 100
                          item.fphte = Math.round((amount + Number.EPSILON) * 100) / 100
                      } else {
                          // 按金额：更改预计合同额，分配合同额不变、对应的占比实时变化
                          let rate = item.fphte / this.model.bchte * 100
                          item.htzb = Math.round((rate + Number.EPSILON) * 100) / 100;
                          // item.htzb = parseFloat(parseFloat(item.fphte) / parseFloat(this.model.bchte)*100).toFixed(2)
                      }
                  })
              }
          },
      convertMoney2() {
        let money = this.model.bchte
        this.$set(this.model, 'bchtedx', convertCurrency(money))
        this.dataSource2.forEach((item, index) => {
                  if(this.model.bchte>0){
                      if(this.model.distributionMethod==1){
                          // 按比例：更改预计合同额，占比不变、对应的分配合同额实时变化
                          // item.fphte = parseFloat(item.htzb*0.01*parseFloat(this.model.bchte)).toFixed(2)
                          let amount = this.model.bchte * item.htzb / 100
                          item.fphte = Math.round((amount + Number.EPSILON) * 100) / 100
                      } else {
                          // 按金额：更改预计合同额，分配合同额不变、对应的占比实时变化
                          let rate = item.fphte / this.model.bchte * 100
                          item.htzb = Math.round((rate + Number.EPSILON) * 100) / 100;
                          // item.htzb = parseFloat(parseFloat(item.fphte) / parseFloat(this.model.bchte)*100).toFixed(2)
                      }
                  } else {
                      if(this.model.distributionMethod==1){
                          // 按比例：更改预计合同额，占比不变、对应的分配合同额实时变化
                          item.fphte = 0
                      } else {
                          // 按金额：更改预计合同额，分配合同额不变、对应的占比实时变化
                          item.htzb = 0
                      }
                  }
        })
      },
      // 监听修改本次合同额数据
      convertMoneyBlur2 (item) {
          let money = Number(this.model.bchte)
          if (this.model.bchte) {
              this.$set(this.model, 'bchte', money.toFixed(2))
          }
      },
      // 选择项目名称
      xmmcInput () {
          this.formDataC = [] // 清空收付款计划
      },
      // 选择合同编号
      htbhChange(val) {
          erpOmcContractManagerFinalQueryById({ id: val.id }).then((res) => {
              if (res.success) {
                  let data = res.result.records || res.result
                  // debugger;
                  this.$set(this.model, 'caId', val.id)
                  this.$set(this.model, 'bpmBizTitle', data.htmc) // 标题
                  this.$set(this.model, 'htmc', data.htmc) // 合同名称
                  this.$set(this.model, 'htlx', data.htlx) // 合同类型
                  this.$set(this.model, 'businessPerformance', data.businessPerformance) // 经营绩效
                  // fix:BUG#4955 合同变更-当合同类型为付款合同，带出的委托方、受托方信息错误 start
                  // fix:BUG#4955 合同变更-当合同类型为付款合同，带出的委托方、受托方信息错误 end
                  this.$set(this.model, 'xmmc', data.xmmc) // 项目名称
                  this.$set(this.model, 'jytd', data.jytd) // 经营团队
                  this.$set(this.model, 'businessCompanyId', data.businessCompanyId) // 经营公司
                  this.$set(this.model, 'yjgsnd', data.yjgsnd)// 业绩归属年度
                  this.$set(this.model, 'qddw', data.qddw) // 签订单位
                  this.$set(this.model, 'xmcjr', data.xmcjr) // 项目承认人
                  this.$set(this.model, 'yzdw', data.yzdw)// 业主单位
                  this.$set(this.model, 'lxr', data.lxr)// 联系人
                  this.cust_lxr = 'erp_omc_customer_manager_contact,lxr,id,del_flag=0 and main_id=\'' + this.model.yzdw + '\'';
                  this.$set(this.model, 'lxfs', data.lxfs) // 联系方式
                  this.$set(this.model, 'qdrq', data.qdrq)// 签订日期
                  this.$set(this.model, 'sfyz', String(data.sfyz))// 是否用印
                  this.$set(this.model, 'signSealWay', data.signSealWay)// 用印类型
                  this.$set(this.model, 'signFile', data.signFile)// 用印文件
                  if(data.sfyz == 1){
                      this.$set(this.model, 'yzlx', data.yzlx) // 印章类型
                      this.$set(this.model, 'yyfs', data.yyfs)// 用印份数
                  } else {
                      this.$set(this.model, 'yzlx', null) // 印章类型
                      this.$set(this.model, 'yyfs', null)// 用印份数
                      this.handleRules(this.model.sfyz)
                      this.$set(this.model, 'noFormalContract', data.noFormalContract)// 是否正式合同
                  }
                  this.$set(this.model, 'sfcd', data.sfcd)// 是否存档
                  if(data.sfcd==1){
                      this.$set(this.model, 'cdfs', data.cdfs)// 存档份数
                  } else {
                      this.$set(this.model, 'cdfs', '')// 存档份数
                      this.handleRules2(this.model.sfcd)
                  }
                  this.$forceUpdate()
                  this.$set(this.model, 'glskht', data.glskht) // 关联收款合同
                  this.glhtFlag = data.glskht == '1'
                  this.$set(this.model, 'skhtmc', data.skhtmc) // 收款合同名称
                  // this.$set(this.model, 'jf', data.yzdw) // 甲方
                  this.$set(this.model, 'jf', data.jf)// 甲方
                  this.$set(this.model, 'yf', data.yf)// 已方
                  // this.$set(this.model, 'yf', data.qddw) // 已方
                  this.$set(this.model, 'skhte', data.skhte)// 收款合同额
                  this.$set(this.model, 'skhtedx', data.skhtedx)// 收款合同额大写
                  let bchte = data.bchte;
                  // if (data.bchte) {
                  //   bchte = data.bchte / 100
                  // }
  
                  this.$set(this.model, 'bchte', bchte)
                  this.$set(this.model, 'bchtedx', data.bchtedx)
                  this.$set(this.model, 'fwqx', data.fwqx)
                  this.$set(this.model, 'fwqxEnd', data.fwqxEnd)
                  // 服务期限
                  if (!!this.model.fwqx && !!this.model.fwqxEnd) {
                      this.createTime = []
                      this.createTime.push(this.model.fwqx)
                      this.createTime.push(this.model.fwqxEnd)
                  } else {
                      this.createTime = []
                  }
                  this.$set(this.model, 'bz', data.bz) // 备注
                  this.$set(this.model, 'yjxx', data.yjxx) // 邮寄信息
                  this.$set(this.model, 'xgfj', data.xgfj) // 相关附件
                  this.$set(this.model, 'htbh', data.htbh) // 合同编号
                  this.$set(this.model, 'xmbh', data.xmbh) // 合同编号
  
                  this.$set(this.model, 'isCategoryType', data.isCategoryType) // 是否采购类
                  this.$set(this.model, 'provisionType', data.provisionType) // 采购类型
                  this.$set(this.model, 'calibrationId', data.calibrationId) // 定标结果确认单
                  this.$set(this.model, 'purchaseApplyId', data.purchaseApplyId) // 采购申请单
                  // this.handleChangeCategory(data.isCategoryType)
                  if (data.isCategoryType == '1') {
                      this.handleChangeProvisionType(data.provisionType)
                  }
                  // this.$set(this.model, 'bglx', data.bglx)
                  this.$set(this.model, 'sfbgkxx', data.sfbgkxx)
                  // this.$set(this.model, 'proposer', data.proposer)
                  // this.$set(this.model, 'proposerDeptId', data.proposerDeptId)
                  this.$set(this, 'isFkht', data.htlx != '1')
                  this.$set(this.model, 'involveMultiple', data.involveMultiple)
                  this.$set(this, 'involveMultipleFlag', data.involveMultiple == 1)
                  if(this.model.sfyz == '1'){
                      this.$delete(this.rules,'masterCopy')
                  } else {
                      this.$set(this.rules,'masterCopy',[{ required: true, message: '请上传合同原件!' }])
                  }
                  this.$set(this.model, 'masterCopy', data.masterCopy) // 合同原件
                  this.$set(this.model, 'bail', '0.00')
                  this.$set(this.model,'distributionMethod',data.distributionMethod || '')
                  // 收款计划
                  erpOmcContractManagerPlanFinalList({ mainId: val.id }).then((res) => {
                      if (res.success) {
                          // res.result数组中的planTaskList数组中拼接categoryName形成款项关联任务
                          res.result.map((value, index) => {
                              res.result[index].taskId_dictText = '' // 首先款项关联任务字段默认为空
                              // 遍历planTaskList数组赋值给taskId_dictText
                              res.result[index].taskId_dictText = value.planTaskList && value.planTaskList.length ? (value.planTaskList.map((obj, ind)=>{
                                  value.planTaskList[ind].finalId = obj.id
                                  return obj.categoryName
                              }).join(",")):'';
                          })
                        this.formDataC = res.result.records || res.result
                        if (this.formDataC.length > 0) {
                              this.formDataC.forEach((item, index) => {
                                  item.finalId = item.id
                              })
                        }
                      }
                  })
                  var params = {
                      preProjectId: data.xmmc,
                      feeCategory: '2',
                      bpmStatus: '3'
                  }
                  // 查看项目保证金
                  erpFinanceProjectDepositBillqueryByEntity( params).then((res) => {
                      if (res.success) {
                        let data = res.result.records || res.result
                        this.$set(this.model, 'bail', data.remittanceAmount)
                      }
                  })
                  // 任务信息
                  // erpOmcContractManagerClassFinalList( { mainId: val.id }).then((res) => {
                  listContractFinalTaskByProjectId( { projectId: data.xmmc }).then((res) => {
                      let arr = res || []
                      this.dataSource2 = []
                      for (let i = 0; i < arr.length; i++) {
                        let d = {
                          id: arr[i].id,
                          ywfl: arr[i].categoryCode,
                          ywmc: arr[i].categoryName,
                          htzb: arr[i].contractRate,
                          fphte: arr[i].contractAmount,
                              
                          sctd: arr[i].productTeam,
                              'shouldPayFlag': arr[i].shouldPayFlag, // 是否应收
                              'distributionType': arr[i].distributionType, // 是否作废
                          sctd_dictText: filterMultiDictText(this.dictOptions['sctd'], arr[i].productTeam + ''),
                          tdfzr: arr[i].teamLeader,
                          tdfzr_dictText: filterMultiDictText(this.dictOptions['tdfzr'], arr[i].teamLeader + ''),
                          projectTaskId: arr[i].id,
                          cutContractAmount: arr[i].cutContractAmount,
                              productCompanyId: arr[i].productCompanyId
                        }
                          this.dataSource2.push(d);
                      }
                      // if (res.success) {
                        // this.dataSource2 = res.result.records || res.result
                        // this.dataSource2.forEach((item, index) => {
                              // item.finalId = item.id
                              // if (this.model.bchte && item.htzb) {
                              // 	let amount = this.model.bchte * item.htzb / 100
                              // 	item.fphte = Math.round((amount + Number.EPSILON) * 100) / 100;
                              // }
                        // })
                      // }
                  }),
                  // 项目赋值
                  erpOmcProjectId( { id: data.xmmc }).then((res) => {
                      if (res.success) {
                        let data = res.result.records || res.result
                        this.$set(this, 'projectName', data.projectName); // 项目名称
                      }
                  }),
                  // 受托方信息
                  erpOmcContractManagerTrusteeFinalList( { mainId: val.id }).then((res) => {
                      if (res.success) {
                          this.formDataB = res.result.records || res.result
                          this.formDataB.forEach((item, index) => {
                            item.finalId = item.id
                          })
                      }
                  }),
                  // 委托方信息
                  erpOmcContractManagerEntrustFinalList( { mainId: val.id }).then((res) => {
                      if (res.success) {
                          this.formDataA = res.result.records || res.result
                          this.formDataA.forEach((item, index) => {
                            item.finalId = item.id
                          })
                      }
                  })
              }
          })
      },
      
      // 选择业主单位
      yzdwChange() {
          this.$set(this.model, 'lxr', undefined);
          this.$set(this.model, 'lxfs', undefined);
          this.cust_lxr = 'erp_omc_customer_manager_contact,lxr,id,del_flag=0 and main_id=\'' + this.model.yzdw + '\'';
      },
      
      // 选择联系人
      lxrChange(val) {
          erpOmcCustomerManagerContactId({ id: val }).then((res) => {
              if (res.success) {
                  let data = res.result.records || res.result
                  this.$set(this.model, 'lxr', val)
                  this.$set(this.model, 'lxfs', data.lxfs)
              }
          })
      },
      
      xmmcChange({ id: val }) {
              if (!val){
                  this.model.calibrationId  = null
              }
        erpOmcProjectId({ id: val }).then((res) => {
          if (res.success) {
            let data = res.result.records || res.result
            this.$set(this.model, 'calibrationId', null) // 定标结果确认单
            this.$set(this.model, 'yzdw', data.ownerUnit) // 业主单位
            this.$set(this.model, 'bail', '0')
            // debugger;
            // this.model.lxdh = data.lxfs;
            this.$set(this.model, 'xmbh', data.finalNo) // 项目编号
                      this.$set(this.model, 'jytd', data.oldTeamId?data.oldTeamId:data.teamName) // 经营团队
                      this.$set(this.model, 'businessCompanyId', data.businessCompanyId) // 经营公司
            this.$set(this.model, 'yjgsnd', data.year) // 业绩归属年度
            this.$set(this.model, 'qddw', data.signUnit) // 签定单位
            this.$set(this.model, 'xmcjr', data.undertaker) // 项目承接人
            this.$set(this.model, 'lxfs', data.contactTel) // 联系方式
            this.cust_lxr = "erp_omc_customer_manager_contact,lxr,id,del_flag=0 and main_id='" + this.model.yzdw + "'"
            this.$set(this.model, 'lxr', data.contacts) // 联系人
                      this.$set(this.model,'distributionMethod',data.distributionMethod || '')
            this.projectName = data.projectName
            // 任务信息
            relationTaskList({ pageNo:1,pageSize: 999,projectId: data.id,distributionType: '!cancel' }).then((res) => {
              this.dataSource2 = []
              if (res.success) {
                let data = res.result.records || res.result
                for (let i = 0; i < data.length; i++) {
                  let d = {
                    id: data[i].id,
                    ywfl: data[i].categoryCode,
                    ywmc: data[i].categoryName,
                    htzb: data[i].contractRate,
                    fphte: data[i].contractAmount,
                    sctd: data[i].productTeam,
                    sctd_dictText: data[i].productTeam_dictText,
                    tdfzr: data[i].teamLeader,
                    tdfzr_dictText: data[i].teamLeader_dictText,
                    projectTaskId: data[i].id,
                  }
                                  this.dataSource2.push(d);
                  // let index = this.dataSource2.findIndex((item) => item.ywfl == d.ywfl)
                  // if (index > -1) {
                  //   this.dataSource2.splice(index, 1, d)
                  // } else {
                  //   this.dataSource2.push(d)
                  // }
                }
                              this.changeMoney()
              }
            })
            var params = {
              preProjectId: data.id,
              feeCategory: '2',
              bpmStatus: '3',
            }
            // 查看项目保证金
            erpFinanceProjectDepositBillqueryByEntity(params).then((res) => {
              if (res.success) {
                let data = res.result.records || res.result
                this.$set(this.model, 'bail', data.remittanceAmount)
              }
            })
          }
        })
      },
      handleCopyFormA([item, index]) {
        this.formDataA.push({
          ...item,
        })
        this.$refs.uToast.show({
            message:'复制成功!'
        })
      },
      handleEditFormA([item, index]) {
        this.basicFormA = { ...item }
        this.index = index
        this.showFormModalA = true
              this.$nextTick(() => {
                  this.openFormModalA()
              })
      },
      handleRemoveFormA(item) {
        this.formDataA = this.formDataA.filter((i) => i !== item)
      },
      closeFormModalA() {
        this.$refs.dataFormA.reset()
        this.basicFormA = {}
        this.index = null
              this.showFormModalA = false
      },
      openFormModalA() {
        this.$refs.dataFormA.basicForm = Object.assign({},this.basicFormA)
      },
      handleCopyFormB([item, index]) {
        this.formDataB.push({
          ...item,
        })
        this.$refs.uToast.show({
            message:'复制成功!'
        })
      },
      addFormA() {
        this.index = null
              this.basicFormA = {}
        this.showFormModalA = true
      },
      /**
       * 子表单新增点击确认
       */
      handleFormSubmitA([data, index]) {
        this.showFormModalA = false
        if (typeof index === 'number') {
          this.$set(this.formDataA, index, data)
        } else {
          this.formDataA.push(data)
        }
        // this.initBuyerInfo()
      },
      handleEditFormB([item, index]) {
        this.basicFormB = { ...item }
        this.index = index
        this.showFormModalB = true
              this.$nextTick(() => {
                  this.openFormModalB()
              })
      },
      handleRemoveFormB(item) {
        this.formDataB = this.formDataB.filter((i) => i !== item)
      },
      closeFormModalB() {
        this.$refs.dataFormB.reset()
        this.basicFormB = {}
        this.index = null
              this.showFormModalB = false
      },
      openFormModalB() {
        this.$refs.dataFormB.basicForm = Object.assign({},this.basicFormB)
      },
      addFormB() {
        this.index = null
              this.basicFormB = {}
        this.showFormModalB = true
      },
      /**
       * 子表单新增点击确认
       */
      handleFormSubmitB([data, index]) {
        this.showFormModalB = false
        if (typeof index === 'number') {
          this.$set(this.formDataB, index, data)
        } else {
          this.formDataB.push(data)
        }
        // this.initBuyerInfo()
      },
      handleEditFormC([item, index]) {
        this.basicFormC = { ...item }
        this.index = index
        this.showFormModalC = true
              this.$nextTick(() => {
                  this.openFormModalC()
              })
      },
      handleRemoveFormC(item) {
        this.formDataC = this.formDataC.filter((i) => i !== item)
      },
      closeFormModalC() {
        this.$refs.dataFormC.reset()
        this.basicFormC = {}
        this.index = null
              this.showFormModalC = false
      },
      openFormModalC() {
        this.$refs.dataFormC.basicForm = Object.assign({},this.basicFormC)
              this.$refs.dataFormC.formDataC = this.basicFormC.planTaskList || []
      },
      handleCopyFormC([item, index]) {
        this.formDataC.push({
          ...item,
        })
        this.$refs.uToast.show({
            message:'复制成功!'
        })
      },
      addFormC() {
        this.index = null
              this.basicFormC = {}
        this.showFormModalC = true
      },
      /**
       * 子表单新增点击确认
       */
      handleFormSubmitC([data, index]) {
        this.showFormModalC = false
        if (typeof index === 'number') {
          this.$set(this.formDataC, index, data)
        } else {
          this.formDataC.push(data)
        }
        // this.initBuyerInfo()
      },
      // queryBillByProject(item) {
      //   this.$set(this.model, 'applicant', item.signUnit)
      //   this.$set(this.model, 'projectYear', item.year)
      //   this.$set(this.model, 'projectBusiTeamId', item.teamName)
      //   queryBillByProject({ projectId: this.model.projectId }).then((res) => {
      //     if (res.success) {
      //       let data = res.result
      //       if (data) {
      //         this.$set(this.model, 'projectPaidTotalAmount', data.projectTotalAmount)
      //         this.projectPaidTotalAmount = data.projectTotalAmount
      //         this.constructTotalAmount = data.constructAmount
      //       }
      //     }
      //   })
      // },
      // 获取单据编号
      async initBillNo() {
        const res = await gainBillNo({ prefix: 'HT', subSystemCode: '05' })
        this.model.htbh = res.result
        // this.model.bpmBizTitle = this.userInfo?.employee?.name + '-' + this.model.htbh //标题
      },
      // 初始化新增需要的数据
      initForm() {
        this.model.proposer = this.userInfo.empId //当前登录人
        this.model.proposerDeptId = this.userInfo.deptId //当前登录人部门
        this.model.createTime = moment().format('YYYY-MM-DD HH:mm:ss')
      },
      async initInfo() {
        const response = await info({ id: this.id })
        const data = await response?.result || {}
              this.model = Object.assign({}, data)
              this.$set(this.model, 'bchtedx', convertCurrency(this.model.bchte))
              this.$set(this.model,'bail',(data.bail === null ||data.bail === undefined || data.bail === '') ?'':String(data.bail))
              this.$set(this.model,'sfyz',String(data.sfyz))
              this.projectName = this.model.xmmc_dictText
              const resA = await erpOmcContractManagerEntrustListAll({ mainId: this.model.id })
              this.formDataA = resA.result.records || resA.result
              const resB = await erpOmcContractManagerTrusteeListAll({ mainId: this.model.id })
              this.formDataB = resB.result.records || resB.result
              const resC = await erpOmcContractManagerPlanListAll({ mainId: this.model.id })
              // resC.result数组中的planTaskList数组中拼接categoryName形成款项关联任务
              resC.result.map((value, index) => {
                  resC.result[index].taskId_dictText = '' // 首先款项关联任务字段默认为空
                  // 遍历planTaskList数组赋值给taskId_dictText
                  resC.result[index].taskId_dictText = value.planTaskList && value.planTaskList.length ? (value.planTaskList.map((obj)=>{return obj.categoryName }).join(",")):'';
              })
              this.formDataC = resC.result.records || resC.result
              const resData = await erpOmcContractManagerClassListAll({ mainId: this.model.id })
              this.dataSource2 = resData.result.records || resData.result
              this.dataSource2.forEach((item, index) => {
                  if (this.model.bchte) {
                      if (this.model.distributionMethod == 1) {
                          // 按比例：更改预计合同额，占比不变、对应的分配合同额实时变化
                          // item.fphte = parseFloat(item.htzb*0.01*parseFloat(this.model.bchte)).toFixed(2)
                          let amount = this.model.bchte * item.htzb / 100
                          item.fphte = Math.round((amount + Number.EPSILON) * 100) / 100
                      } else {
                          // 按金额：更改预计合同额，分配合同额不变、对应的占比实时变化
                          let rate = item.fphte / this.model.bchte * 100
                          item.htzb = Math.round((rate + Number.EPSILON) * 100) / 100;
                          // item.htzb = parseFloat(parseFloat(item.fphte) / parseFloat(this.model.bchte)*100).toFixed(2)
                      }
                  } else {
                      if (this.model.distributionMethod == 1) {
                          // 按比例：更改预计合同额，占比不变、对应的分配合同额实时变化
                          item.fphte = 0
                      } else {
                          // 按金额：更改预计合同额，分配合同额不变、对应的占比实时变化
                          item.htzb = 0
                      }
                  }
              })
              this.handleRules()
              this.handleRules2()
              this.cust_lxr = 'erp_omc_customer_manager_contact,lxr,id,del_flag=0 and main_id=\'' + this.model.yzdw + '\'';
              const keys = ['bail','sfyz']
              keys.forEach(val => {
                  if(typeof this.model[val] == 'number'){
                      this.model[val] = String(this.model[val])
                  }
              })
      },
      
          // 获取流程列表
        //   getProcessList (id) {
        //       if (this.isSubmit) {
        //           checkContractById({ id }).then(res => {
        //               if (res.success) {
        //                   this.$refs.processConfig.showPopup = true
        //                   this.$refs.processConfig.formUrl = this.formUrl
        //                   this.$refs.processConfig.formUrlMobile = this.formUrlMobile
        //                   this.$refs.processConfig.flowCode = this.flowCode
        //                   this.$refs.processConfig.edit(id, this.processId, this.beanName)
        //               } else {
        //                   this.$refs.uToast.show({
        //                       message: res.message,
        //                       complete () {
        //                           if (getCurrentPages().length > 1) {
        //                               uni.navigateBack()
        //                           } else {
        //                               uni.reLaunch({
        //                                   url: '/pages/home/home'
        //                               })
        //                           }
                                  
        //                       }
        //                   })
        //               }
        //           })
        //       }
        //   },
          getProcessList (id) {
              if (this.isSubmit) {
                 this.$refs.processConfig.showPopup = true
                 this.$refs.processConfig.formUrl = this.formUrl
                 this.$refs.processConfig.formUrlMobile = this.formUrlMobile
                 this.$refs.processConfig.flowCode = this.flowCode
                 this.$refs.processConfig.edit(id, this.processId, this.beanName)
                    
              }
          },
          // 提交流程成功
          onOk () {
              this.$refs.uToast.show({
                  message: '提交成功',
                  type: 'success',
                  complete () {
                      if (getCurrentPages().length > 1) {
                          uni.navigateBack()
                      } else {
                          uni.reLaunch({
                              url: '/pages/home/home'
                          })
                      }
                      
                  }
              })
          },
      valdateContractMoney() {
        let planSum = 0
        this.formDataC.forEach((data) => {
          planSum += Number(data.je)
        })
        // 迭代11 TASK#3763 2.收付款计划栏金额与合同总金额不对等时不可以发起，需要校验核对收付款计划金额和合同总金额
        if (Number(this.model.bchte).toFixed(2) != planSum.toFixed(2)) {
          this.$refs.uToast.show({
              message:'计划总金额与合同金额不对等!'
          })
          return false
        }
        // 付款合同的本次合同额应该只是对外的任务的金额，不能校验本次合同额等于所有任务的总额
        if (this.model.htlx === 1 || this.model.htlx === '1') {
                  if(this.model.distributionMethod==1){
                      let rate = 0
                      this.dataSource2.forEach(val => {
                          rate += parseFloat(val.htzb)
                      })
                      if (rate != 100) {
                          this.$refs.uToast.show({
                              message:'合同占比相加不等于100%，请重新填写!'
                          })
                          return false;
                      }
                  } else {
                      let total = 0
                      this.dataSource2.forEach((val) => {
                        total += parseFloat(val.fphte)
                      })
                      if (total.toFixed(2) != parseFloat(this.model.bchte).toFixed(2)) {
                          this.$refs.uToast.show({
                              message:'所有分配金额总计和本次合同额不相等，请重新填写!'
                          })
                        return false
                      }
                  }
        }
        return true
      },
      // 校验委托方和受托方子表数据合法性 委托方和受托方列表需要校验两个分别必须至少有一条数据 是否为收付款单位有各且仅有一个
      validateClientDetailAndTrusteeDetail() {
        if (!this.formDataA.length) {
          this.$refs.uToast.show({
              message:'请填写委托方信息!'
          })
          return false
        }
        if (!this.formDataB.length) {
          this.$refs.uToast.show({
              message:'请填写受托方信息!'
          })
          return false
        }
        const hasFkList = this.formDataA.filter((i) => i.isFk === '1')
        // if (hasFkList.length !== 1) {
        //   this.$refs.uToast.show({
        //   	message:'委托方有且仅有一个是付款单位!'
        //   })
        //   return false
        // }
            //   if (hasFkList.length <= 0) {
            //     this.$refs.uToast.show({
            //           message:'委托方必须有一个是付款单位!'
            //       })
            //     return false
            //   }
              // 判断当选择是否用印为是且用印类型是电子签章的时候判断是否填写了盖章人信息和联系方式信息
              // let psnName = this.formDataA.filter(item => item.psnName);
              // let psnMobile = this.formDataA.filter(item => item.psnMobile);
              if (this.model.sfyz && this.model.sfyz == 1 && this.model.signSealWay == 'online') {
                  // 当主表选择了电子签章
                  for (var i = 0; i < this.formDataA.length; i++) {
                      if (this.formDataA[i].isSignSeal && this.formDataA[i].isSignSeal == 1) {
                          if (!this.formDataA[i].psnName || !this.formDataA[i].psnMobile) {
                              this.$refs.uToast.show({
                                  message:'请填写委托方联系人和联系方式!'
                              })
                              return
                          }
                      }
                  }
              }
        const hasSkList = this.formDataB.filter((i) => i.isSk === '1')
        // if (hasSkList.length !== 1) {
        //   this.$refs.uToast.show({
        //       message:'受托方有且仅有一个是收款单位!'
        //   })
        //   return false
        // }
              // 判断当选择是否用印为是且用印类型是电子签章的时候判断是否填写了盖章人信息和联系方式信息
              let psnName = this.formDataB.filter(item => !item.psnName);
              let psnMobile = this.formDataB.filter(item => !item.psnMobile);
              if (this.model.sfyz && this.model.sfyz == 1 && this.model.signSealWay == 'online') {
                  // 当主表选择了电子签章
                  if (psnName.length || psnMobile.length) {
                      this.$refs.uToast.show({
                          message:'请填写受托方联系人和联系方式!'
                      })
                  return false;
                  }
              }
        return true
      },
      validateForm() {
        return this.$refs.form.validate().then(async () => {
        //   if (!this.valdateContractMoney()) {
        //     return Promise.reject('金额校验失败')
        //   }
          if (!this.validateClientDetailAndTrusteeDetail()) {
            return Promise.reject('信息校验失败')
          }
                //   if (!this.handleJudgePayment()) {
                //       return Promise.reject('收付款计划信息校验失败')
                //   }
          return Promise.resolve()
        })
      },
          // 判断需分配款项信息中的数据是否达到100%，如果达到则提交，否则提示需分配款项信息中的数据未达到100%
        //   handleJudgePayment() {
        //       var isTrue = true // true为通过，false为不通过
        //       // var _this = this
        //       var text = ''
        //       if (this.formDataC && this.formDataC.length > 0) {
        //           this.formDataC.forEach((item, index) => {
        //               if (item.collectMoneyStatus != '已生成') {
        //                   if (item && item.planTaskList && item.planTaskList.length > 0) {
        //                       // 判断item1中的 paymentRate之和是否等于100%
        //                       const listTotal = item.planTaskList.reduce((total, item1) => {
        //                           const paymentRate = Number(item1.paymentRate) || 0;
        //                           const decimalContractRate = new Decimal(paymentRate);
        //                           return total.plus(decimalContractRate);
        //                       }, new Decimal(0)).toNumber(); // 解决浮点数导致两者不相等
        //                       if (listTotal != 100) {
        //                           text = '收付款计划中，款项绑定的任务，款项分配占比没有达到100%！'
        //                           isTrue = false
        //                       }
        //                   } else {
        //                       text = '收付款计划中、款项未绑定任务、需绑定任务！'
        //                       isTrue = false // 没有任务时，不允许通过
        //                   }
        //               }
        //           })
        //       } else {
        //           text = '请填写收付款计划！'
        //           isTrue = false
        //       }
        //       if (!isTrue) {
        //           this.$refs.uToast.show({
        //               message:text
        //           })
        //       }
        //       return isTrue
        //   },
      //处理首付款计划，新增sortOrder字段
      handelPlanList(list){
          for (let i = 0; i < list.length; i++) {
              list[i].sortOrder=i;
          }
          return list;
      },
      async onSubmit() {
        //   const hasNullCutContractAmount = this.dataSource2.some(item => item.cutContractAmount === '')
        //   if(hasNullCutContractAmount) return  this.$refs.uToast.show({message: '请填写切割合同额' }) 
        await this.validateForm()
        let url = ''
          this.model.bpmBizTitle =  (this.model.htmc? this.model.htmc+ ' - ':'') + this.userInfo?.employee?.name + '-' + this.model.htbh
          if (this.id) {
              url = await edit
          } else {
              url = await add
          }
          
        // if (!this.model.id) {
        // 	url = await erpOmcPlatformAccountAdd(this.model)
        // } else {
        // 	url = await erpOmcPlatformAccountEdit(this.model)
        // }
        try {
          this.isSubmit = true
          const response = await url({
            ...this.model,
            entrustList: this.formDataA,
            trusteeList: this.formDataB,
            planList: this.handelPlanList(this.formDataC),
            classList: this.dataSource2,
          })
          this.$refs.uToast.show({
              message:response.message
          })
          if (response.success) {
            if (this.model.id) {
                await this.getProcessList(this.model.id)
            } else {
                // 判断添加的时候是否有返回id值
                if (response.result) {
                    await this.getProcessList(response.result)
                }
            }
          }
        }  finally {
          this.isSubmit = false
              // error
        }
      },
      async onDraft() {
        // await this.validateForm()
        let url = ''
          this.model.bpmBizTitle =  (this.projectName? this.projectName+ ' - ':'') + this.userInfo?.employee?.name + '-' + this.model.htbh
        if (this.id) {
            url = await edit
        } else {
            url = await add
        }
        try {
          this.isSubmit = true
          const response = await url({
            ...this.model,
            entrustList: this.formDataA,
            trusteeList: this.formDataB,
            planList: this.handelPlanList(this.formDataC),
            classList: this.dataSource2,
          })
          if (response.success) {
           this.$refs.uToast.show({
                message: response.message,
                type: 'default',
                complete () {
                    this.isSubmit = false
                    if (getCurrentPages().length > 1) {
                        uni.navigateBack()
                    } else {
                        uni.reLaunch({
                            url: '/pages/home/home'
                        })
                    }
                    
                }
            })
          }
        } finally {
              // error
        }
      },
    }
  }
  </script>
  
  <style scoped lang="scss">
  @import url('@/assets/inputStyle.scss');
  .trip-form-data {
    ::v-deep {
      .u-form-item__body {
        padding-top: 2px;
        padding-bottom: 2px;
      }
    }
  }
  .checkbox-item {
    display: flex;
    align-items: center;
  }
  </style>
  